package com.blue.wechat.invoke.model.menu;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.util.JsonUtil;
import com.blue.wechat.invoke.model.Json;

public class Menu implements Json
{
	private List<MenuItem> button = new ArrayList<>();

	public Menu()
	{
	}

	public void add(MenuItem item)
	{
		button.add(item);
	}

	public void addAll(Collection<MenuItem> itemList)
	{
		button.addAll(itemList);
	}

	public void add(String name, MenuType type, String url, String key)
	{
		MenuItem item = new MenuItem();
		item.setName(name);
		item.setType(type);
		item.setUrl(url);
		item.setKey(key);
		button.add(item);
	}

	public void add(String name, MenuType type, String url, String key,
			List<MenuItem> subList)
	{
		MenuItem item = new MenuItem();
		item.setName(name);
		item.setType(type);
		item.setUrl(url);
		item.setKey(key);
		item.setSubButton(subList);
		button.add(item);
	}

	public List<MenuItem> getButton()
	{
		return button;
	}

	public void setButton(List<MenuItem> button)
	{
		this.button = button;
	}

	@Override
	public String toJson()
	{
		return JsonUtil.output(this);
	}

	private void putButton(JSONObject json, MenuItem item)
	{
		MenuType type = item.getType();
		json.put("type", type.name().toLowerCase());
		if (type == MenuType.view)
			json.put("url", item.getUrl());
		else
			json.put("key", item.getKey());
	}

	@Override
	public String toString()
	{
		JSONObject root = new JSONObject();
		JSONArray buttons = new JSONArray();
		root.put("button", button);

		for (MenuItem item : button)
		{
			JSONObject json = new JSONObject();
			buttons.add(json);
			json.put("name", item.getName());

			if (item.getSubButton().isEmpty())
			{
				this.putButton(json, item);
			}
			else
			{
				JSONArray subButton = new JSONArray();
				json.put("sub_button", subButton);
				for (MenuItem sub : item.getSubButton())
				{
					JSONObject subJson = new JSONObject();
					subButton.add(subJson);
					subJson.put("name", sub.getName());
					this.putButton(subJson, sub);
				}
			}

		}

		return root.toJSONString();
	}

}
